package com.suma.platform.core.util;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author suma
 * @date 2018/2/8 上午9:24
 */
public class PrintABCThread2 implements Runnable {

	private ReentrantLock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	private int state = 0;

	@Override
	public void run() {

		String name = Thread.currentThread().getName();
		lock.lock();
		try {
			for (int i = 0; i < 10; i++) {
				if ("A".equals(name)) {
					while (state % 3 != 1) {
						condition.await();
					}
				}
				if ("B".equals(name)) {
					while (state % 3 != 2) {
						condition.await();
					}
				}
				if ("C".equals(name)) {
					while (state % 3 != 0) {
						condition.await();
					}
				}
				state++;
				System.out.println(name);
				condition.signalAll();// 通知正在等待的线程，此时有可能已经满足条件
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();// 记得要释放锁
		}

	}

	public static void main(String[] args) {
//		ExecutorService service = new ThreadPoolExecutor(3, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
		PrintABCThread2 task = new PrintABCThread2();
		Thread thread1 = new Thread(task);
		Thread thread2 = new Thread(task);
		Thread thread3 = new Thread(task);
		thread1.setName("A");
		thread2.setName("B");
		thread3.setName("C");
		thread1.start();
		thread2.start();
		thread3.start();
	}
}
